import * as api from '../../utils/api.js';
const DatePickerUtil = require('../../utils/DatePicker')
Page({
  data: {
    categoryList: [],
    categoryIndex: 0,
    doorTypeList: ['木门','钢门'],
    doorType: 0,
    formData: {},
    // 提交的经纬度
    latitude: '',
    longitude: '',
    // 选择地区的中心经纬度
    tempLatLng: {
      lat: '',
      lng: ''
    },
    fileList: [],
    // DatePicker的内容
    time:'选择预约时间',
    multiArray:[],//piker的item项
    multiIndex:[],//当前选择列的下标
    year:'',//选择的年
    month:'',//选择的月
    day:'',//选择的日
    hour:'',//选择的时
    minute:'',//选择的分
    region: ['', '', ''],
  },
  bindCategoryChange(e) {
    this.setData({
      categoryIndex:e.detail.value
    })
  },
  bindDoorTypeChange(e) {
    console.log(e.detail.value)
    this.setData({
      doorType: e.detail.value
    })
  },
  getAreaByCode(code) {
    const that = this
    console.log({code})
    api.getAreaByCode(code)
      .then(res => {
        const region = res.data
        that.setData({
          'formData.province_id' : region.province.id,
          'formData.city_id' : region.city.id,
          'formData.area_id' : region.area.id,
          'tempLatLng.lat': region.area.lat,
          'tempLatLng.lng': region.area.lng
        })
      }).catch(err => console.log(err))
  },
  bindKeyInput: function (e) {
    const name = e.currentTarget.dataset.name
    const value = e.detail.value
    let formData = this.data.formData
    formData[name] = value
    this.setData({formData})
  },
  bindRegionChange(e) {
    const region = e.detail.value
    this.setData({
      region
    })
    const code = e.detail.postcode
    this.getAreaByCode(code)
  },
  bindDateChange(f) {
    this.setData({
      date:f.detail.value
    })
  },
  chooseLocation() {
    console.log('chooseLocation')
    const that = this
    const latitude = this.data.latitude ? this.data.latitude : (this.data.tempLatLng.lat ? this.data.tempLatLng.lat : '')
    const longitude = this.data.longitude ? this.data.longitude : (this.data.tempLatLng.lng ? this.data.tempLatLng.lng : '')
    let options = {}
    if (latitude) options.latitude = latitude
    if (longitude) options.longitude = longitude
    options.success = function (res) {
      console.log(res)
      that.setData({
        latitude: res.latitude.toFixed(5),
        longitude: res.longitude.toFixed(5),
        'formData.address': res.address
      })
    } 
    options.fail = function (err) {
      console.log(err)
    }
    wx.chooseLocation(options)
  },
  afterRead(event) {
    const that = this
    const { file } = event.detail;
    console.log(file)
    api.upload(file.url)
      .then(res => {
        console.log(res)
        let fileList = this.data.fileList
        const url = res.data.url
        fileList.push({ ...file, url })
        that.setData({
          fileList
        })
      }).catch(err => {
        console.log(err)
      })
  },
  delFile(event) {
    const index = event.detail.index
    let fileList = this.data.fileList
    fileList.splice(index, 1)
    this.setData({fileList})
  },
  submit() {
    console.log(this.data)
    const category_id = this.data.categoryList[this.data.categoryIndex]['id']
    const door_type = this.data.doorType
    const formData = this.data.formData
    const contacts = formData.contacts ?? ''
    const contact_number = formData.contact_number ?? ''
    const province_id = formData.province_id ?? ''
    const city_id = formData.city_id ?? 0
    const area_id = formData.area_id ?? 0
    const address = formData.address ?? ''
    const latitude = this.data.latitude
    const longitude = this.data.longitude
    const pre_book_time = this.data.time.replace('年', '-').replace('月', '-').replace('日', ' ')
    const problem_description = formData.problem_description ?? ''
    const images = this.data.fileList.map(item => item.url)
    api.customerCreateRepairOrder(category_id, door_type, contacts, contact_number, province_id, city_id, area_id, address, latitude, longitude, pre_book_time, problem_description, images)
      .then(res => {
        wx.navigateTo({
          url: '/pages/order/repairOrder/index',
        })
      }).catch(err => {
        wx.showToast({
          title: err.msg,
          icon: 'none'
        })
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取 DatePickerUtil 工具下的方法
    var  loadPickerData=DatePickerUtil.loadPickerData()
    var  getCurrentDate=DatePickerUtil.getCurrentDate()
    var  GetMultiIndex=DatePickerUtil.GetMultiIndex() 
    
    //这里写的是为了记录当前时间
    let year=parseInt(getCurrentDate.substring(0,4)); 
    let month=parseInt(getCurrentDate.substring(5,7)); 
    let day=parseInt(getCurrentDate.substring(8,10)); 
    let hour=parseInt(getCurrentDate.substring(11,13));   
    let minute=parseInt(getCurrentDate.substring(14,16)); 
    
    this.setData({  
      multiArray:loadPickerData,//picker数组赋值，格式 [years, months, days, hours, minutes]
      multiIndex:GetMultiIndex,//设置pickerIndex，[0,0,0,0,0]
      time:getCurrentDate, //设置当前时间 ，currentYears+'-'+mm+'-'+dd+' '+hh+':'+min
      year:year,//记录选择的年
      month:month,//记录选择的月
      day:day,//记录选择的日
      hour:hour,//记录选择的时
      minute:minute,//记录选择的分 
    });   
    this.repairCategoryList()
  },
  repairCategoryList() {
    const that = this
    api.repairCategoryList()
      .then(res => {
        const categoryList = res.data
        that.setData({
          categoryList
        })
      }).catch(err => console.log(err))
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
 bindMultiPickerChange: function(e) { //时间日期picker选择改变后，点击确定 
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
    const index = this.data.multiIndex; // 当前选择列的下标
    const year = this.data.multiArray[0][index[0]];
    const month = this.data.multiArray[1][index[1]];
    const day = this.data.multiArray[2][index[2]];
    const hour = this.data.multiArray[3][index[3]];
    const minute = this.data.multiArray[4][index[4]];
    // console.log(`${year}-${month}-${day} ${hour}:${minute}`); 
    
    this.setData({
      time: year+ month+ day + ' ' + hour.replace('时','')+':'+minute.replace('分',''),
      year:year, //记录选择的年
      month:month, //记录选择的月
      day:day, //记录选择的日
      hour:hour, //记录选择的时
      minute:minute, //记录选择的分 
    })
    //console.log(this.data.time); 
  }, 
  bindMultiPickerColumnChange: function(e) { //监听picker的滚动事件
  
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    
    let getCurrentDate = DatePickerUtil.getCurrentDate();//获取现在时间  
    let currentYear = parseInt(getCurrentDate.substring(0,4)); 
    let currentMonth = parseInt(getCurrentDate.substring(5,7)); 
    let currentDay = parseInt(getCurrentDate.substring(8,10)); 
    let currentHour = parseInt(getCurrentDate.substring(11,13));  
    let currentMinute = parseInt(getCurrentDate.substring(14,16)); 
    
    if (e.detail.column == 0) {//修改年份列 
     
      let yearSelected = parseInt(this.data.multiArray[e.detail.column][e.detail.value]);//当前选择的年份
 
      this.setData({ 
        multiIndex:[0,0,0,0,0] ,//设置pickerIndex
        year:yearSelected //当前选择的年份
      });
      
      if(yearSelected == currentYear){//当前选择的年份==当前年份  
        var loadPickerData=DatePickerUtil.loadPickerData();
        
        this.setData({
          multiArray:loadPickerData,//picker数组赋值
          multiIndex:[0,0,0,0,0] //设置pickerIndex
        });
        
      }else{  // 选择的年份！=当前年份 
      
        // 处理月份
        let monthArr=DatePickerUtil.loadMonths(1,12)
        // 处理日期
        let dayArr=DatePickerUtil.loadDays(currentYear,currentMonth,1) 
        // 处理hour
        let  hourArr=DatePickerUtil.loadHours(0,24); 
        // 处理minute
        let  minuteArr=DatePickerUtil.loadMinutes(0,60)
         
        // 给每列赋值回去
        this.setData({
          ['multiArray[1]']: monthArr,
          ['multiArray[2]']: dayArr,
          ['multiArray[3]']: hourArr,
          ['multiArray[4]']: minuteArr
        });
      }
    }
    if (e.detail.column == 1) {//修改月份列
      let mon = parseInt(this.data.multiArray[e.detail.column][e.detail.value]); //当前选择的月份
      this.setData({
        month:mon  // 记录当前列
      })
      
      if(mon==currentMonth){//选择的月份==当前月份 
        if(this.data.year==currentYear){  
        
          // 处理日期
          let dayArr=DatePickerUtil.loadDays(currentYear,mon,currentDay) 
          // 处理hour
          let  hourArr=DatePickerUtil.loadHours(currentHour,24); 
          // 处理minute
          let  minuteArr=DatePickerUtil.loadMinutes(currentMinute,60)

          this.setData({ 
            ['multiArray[2]']:dayArr,
            ['multiArray[3]']: hourArr,
            ['multiArray[4]']: minuteArr
          })
        }else{ 
          // 处理日期
          let dayArr=DatePickerUtil.loadDays(currentYear,mon,1) 
          // 处理hour
          let  hourArr=DatePickerUtil.loadHours(0,24); 
          // 处理minute
          let  minuteArr=DatePickerUtil.loadMinutes(0,60)
          
          this.setData({
            ['multiArray[2]']:dayArr,
            ['multiArray[3]']: hourArr,
            ['multiArray[4]']: minuteArr
          });
        } 
      }else{  // 选择的月份！=当前月份 
         // 处理日期
         let dayArr = DatePickerUtil.loadDays(currentYear,mon,1) // 传入当前年份，当前选择的月份去计算日
         // 处理hour
         let  hourArr = DatePickerUtil.loadHours(0,24); 
         // 处理minute
         let  minuteArr = DatePickerUtil.loadMinutes(0,60)
         
       	 this.setData({
           ['multiArray[2]']:dayArr,
           ['multiArray[3]']: hourArr,
           ['multiArray[4]']: minuteArr
         });
      } 
    } 
    if(e.detail.column == 2) {//修改日
      let dd = parseInt(this.data.multiArray[e.detail.column][e.detail.value]);//当前选择的日
      this.setData({
        day:dd
      })
      if(dd==currentDay){//选择的日==当前日
        if(this.data.year==currentYear&&this.data.month==currentMonth){//选择的是今天 
        
         // 处理hour
         let  hourArr=DatePickerUtil.loadHours(currentHour,24); 
         // 处理minute
         let  minuteArr=DatePickerUtil.loadMinutes(currentMinute,60)
         
         this.setData({
            ['multiArray[3]']: hourArr,
            ['multiArray[4]']: minuteArr
         });
         
        }else{ //选择的不是今天 
          // 处理hour
          let  hourArr=DatePickerUtil.loadHours(0,24); 
          // 处理minute
          let  minuteArr=DatePickerUtil.loadMinutes(0,60)
          
          this.setData({
             ['multiArray[3]']: hourArr,
             ['multiArray[4]']: minuteArr
          });
        }
      }else{  // 选择的日！=当前日 
       // 处理hour
       let  hourArr=DatePickerUtil.loadHours(0,24); 
       // 处理minute
       let  minuteArr=DatePickerUtil.loadMinutes(0,60)
       
       this.setData({
         ['multiArray[3]']: hourArr,
         ['multiArray[4]']: minuteArr
       });
      }
    } 
    if(e.detail.column == 3) {//修改时
      let hh = parseInt(this.data.multiArray[e.detail.column][e.detail.value]); //当前选择的时
      this.setData({
        hour:hh
      })
      if(hh==currentHour){//选择的时==当前时 
        if(this.data.year==currentYear&&this.data.month==currentMonth&&this.data.month==currentMonth){   // 选择的是今天
          
          // 处理minute
            let  minuteArr=DatePickerUtil.loadMinutes(currentMinute,60)
            this.setData({ 
              ['multiArray[4]']: minuteArr
            });
        }else{ // 选择的不是今天
        
          // 处理minute
          let  minuteArr=DatePickerUtil.loadMinutes(0,60)
          this.setData({ 
            ['multiArray[4]']: minuteArr
          });
        } 
      }else{//选择的时！=当前时 
        // 处理minute
        let  minuteArr=DatePickerUtil.loadMinutes(0,60)
        this.setData({ 
          ['multiArray[4]']: minuteArr
        });
      }
    }
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };

    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    data.multiIndex[e.detail.column] = e.detail.value; //将值赋回去
    
    this.setData(data);  //将值赋回去
  }
  })
